/**
 * Copyright (c) 2010-2011 Pierre LABATUT
 *
 * This file is part of multiple-track-player project.
 *
 * multiple-track-player is free software: you can redistribute it and/or modify it
 * under the terms of its license which may be found in the accompanying
 * LICENSE file or <http://code.google.com/p/multiple-track-player/>.
 */
package multitrack.preload;

/**
 * Data conversion method that outdo ShortBuffers in term of performance.
 * The gain is x10, even in -server mode. There a millions of samples and the 
 * NIO call stack are to thick to be efficient.
 * May be replaced NIO buffer wrapping when made efficient.
 * 
 * @author Pierre LABATUT
 */
public class Bits {

    public static int shortToByte(short[] fromBuffer, int fromOffset, int fromLength,
            byte[] toBuffer, int toOffset, boolean isBigEndian) {

        if (isBigEndian) {
            for (int i = fromLength; i != 0; i--) {
                final short s = fromBuffer[fromOffset++];
                toBuffer[toOffset++] = (byte) (s >> 8);
                toBuffer[toOffset++] = (byte) s;
            }
        } else {
            for (int i = fromLength; i != 0; i--) {
                final short s = fromBuffer[fromOffset++];
                toBuffer[toOffset++] = (byte) s;
                toBuffer[toOffset++] = (byte) (s >> 8);
            }
        }
        return fromLength * 2;
    }

    static void byteToShort(byte[] fromBuffer, int fromOffset, int fromLength, short[] toBuffer, int toOffset, boolean isBigEndian) {
        if (isBigEndian) {
            for (int i = fromLength / 2; i != 0; i--) {
                final byte high = fromBuffer[fromOffset++];
                final byte low = fromBuffer[fromOffset++];
                toBuffer[toOffset++] = (short) (high << 8 | (low & 0xff));
            }
        } else {
            for (int i = fromLength / 2; i != 0; i--) {
                final byte low = fromBuffer[fromOffset++];
                final byte high = fromBuffer[fromOffset++];
                toBuffer[toOffset++] = (short) (high << 8 | (low & 0xff));
            }
        }        
    }
}
